package cn.edu.hust.cm.lib;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class OsUtils {

	/**
	 * get current pid
	 * 
	 * @see http://www.oschina.net/code/snippet_724468_16285
	 * @return current pid, or -1 if failed
	 */
	public static int getPid() {
		RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
		// format: "pid@hostname"
		String name = runtime.getName();
		int atIndex = name.indexOf('@');
		if (atIndex > 0) {
			try {
				return Integer.parseInt(name.substring(0, atIndex));
			} catch (NumberFormatException e) {
				// ignore
			}
		}
		return -1;
	}
}
